package sapling.utils;

import com.google.common.base.Charsets;
import org.apache.commons.codec.binary.Hex;

import java.security.GeneralSecurityException;
import java.security.MessageDigest;

/**
 * MD5工具
 * Created by mac on 16/11/22.
 */
public class Md5Util {
    private static final String MD5 = "MD5";

    /**
     * MD5加密
     *
     * @param input 待加密的文本内容
     * @return
     */
    public static String getMd5(String input) {
        return Hex.encodeHexString(digest(input.getBytes(Charsets.UTF_8), MD5, null, 1));
    }


    /**
     * MD5加密
     *
     * @param input 待加密的文本内容
     * @param salt  salt
     * @return
     */
    public static String getMd5(String input, byte[] salt) {
        return Hex.encodeHexString(digest(input.getBytes(Charsets.UTF_8), MD5, salt, 1));
    }


    /**
     * MD5加密
     *
     * @param input      待加密的文本内容
     * @param iterations 加密迭代次数
     * @return
     */
    public static String getMd5(String input, int iterations) {
        return Hex.encodeHexString(digest(input.getBytes(Charsets.UTF_8), MD5, null, iterations));
    }

    /**
     * 对字符串进行散列, 支持md5与sha1算法.
     */
    private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);

            if (salt != null) {
                digest.update(salt);
            }

            byte[] result = digest.digest(input);

            for (int i = 1; i < iterations; i++) {
                digest.reset();
                result = digest.digest(result);
            }
            return result;
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
    }
}
